import { FC, InputHTMLAttributes, useEffect, useRef, useState } from 'react'
import { Button } from '../ui/button'
import { Input } from '../ui/input'
import { toast } from 'sonner'
import { useAxios } from '@/hooks/useAxios'
import { useMutation } from '@tanstack/react-query'
import { FieldValidate } from '../common/FieldValidate'
import { FormAsyncValidateOrFn, FormValidateOrFn, ReactFormExtendedApi } from '@tanstack/react-form'
import dayjs from 'dayjs'
import { Label } from '../ui/label'
interface Props extends InputHTMLAttributes<HTMLInputElement> {
  formObject: ReactFormExtendedApi<
    any,
    FormValidateOrFn<any> | undefined,
    FormValidateOrFn<any> | undefined,
    FormAsyncValidateOrFn<any> | undefined,
    FormValidateOrFn<any> | undefined,
    FormAsyncValidateOrFn<any> | undefined,
    FormValidateOrFn<any> | undefined,
    FormAsyncValidateOrFn<any> | undefined,
    FormAsyncValidateOrFn<any> | undefined,
    unknown
  >
  field: 'email' | 'mobile'
  label?: string
  action: string
}

export const SendCode: FC<Props> = ({ formObject, field, label, action, ...props }) => {
  const sendEndTime = localStorage.getItem('sendCodeTime')
  const [endTime, setEndTime] = useState(sendEndTime ? dayjs(sendEndTime) : dayjs())
  const [currentTime, setCurrentTime] = useState(dayjs())
  const timeoutId = useRef<NodeJS.Timeout | undefined>(undefined)
  const [value, setValue] = useState('')
  const { axiosInstance } = useAxios()
  const sendCodeMutation = useMutation({
    mutationFn: async () => {
      await axiosInstance.post(action, { [field]: value })
      toast('验证码已发送')
    }
  })
  useEffect(() => {
    timeoutId.current = setInterval(() => {
      setCurrentTime(dayjs())
    }, 1000)
    return () => {
      clearInterval(timeoutId.current)
    }
  }, [])
  return (
    <formObject.Field
      name={field}
      children={(fieldInstance) => (
        <>
          {label && <Label htmlFor="email">{label}</Label>}
          <div className="grid grid-cols-[1fr_auto] gap-2">
            <Input
              {...props}
              value={value}
              onChange={(e) => {
                setValue(e.target.value)
                fieldInstance.handleChange(e.target.value)
              }}
              placeholder={`请输入${field === 'email' ? '邮箱' : '手机号'}`}
            />
            <Button
              variant="outline"
              type="button"
              disabled={currentTime < endTime || sendCodeMutation.isPending}
              onClick={() => {
                if (!value)
                  return toast('请输入要绑定的' + ((field as unknown as string) === 'email' ? '邮箱' : '手机号'))
                sendCodeMutation.mutate(undefined, {
                  onSuccess: () => {
                    localStorage.setItem('sendCodeTime', dayjs().add(60, 'second').toISOString())
                    setEndTime(dayjs().add(60, 'second'))
                  }
                })
              }}>
              {currentTime > endTime ? '发送验证码' : '请' + endTime.diff(currentTime, 'second') + '秒后操作'}
            </Button>
          </div>
          <FieldValidate errors={fieldInstance.state.meta.errors} name={fieldInstance.name} />
        </>
      )}
    />
  )
}
